﻿namespace Seagull
{
    /// <summary>
    /// 
    /// </summary>
    public sealed class App
    {
        internal static Assembly[] _assemblies;
        internal static Type[] _effectiveTypes;
        internal static IServiceProvider _provider;
        internal static IServiceCollection _services;

        /// <summary>
        /// 获取项目所有程序集
        /// </summary>
        public static Assembly[] Assemblies => _assemblies;

        /// <summary>
        /// 获取项目所有有效类型
        /// </summary>
        public static Type[] EffectiveTypes => _effectiveTypes;

        /// <summary>
        /// 获取IOC容器服务的实例。
        /// </summary>
        public static IServiceCollection Services => _services;

        /// <summary>
        /// 获取环境对象。
        /// </summary>
        public static Microsoft.Extensions.Hosting.IHostEnvironment HostEnvironment
        {
            get
            {
                var hostEnvironment = _provider.GetService<Microsoft.Extensions.Hosting.IHostEnvironment>();
                return hostEnvironment;
            }
        }

        /// <summary>
        /// 获取请求上下文
        /// </summary>
        public static HttpContext? HttpContext => _provider.GetService<IHttpContextAccessor>()?.HttpContext;

        /// <summary>
        /// 获取服务容器
        /// </summary>
        public static IServiceProvider Provider { get => _provider; }

        /// <summary>
        /// 获取容器内的服务。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>返回类型为
        /// <typeparamref name="T"/>
        /// 的服务对象，如果没有这样的服务，则返回null.</returns>
        public static T? GetService<T>()
        {
            return _provider.GetService<T>();
        }

        /// <summary>
        /// 获取容器内的服务(如果未找到
        /// <typeparamref name="T"/>
        /// 时，框架将抛出异常)。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetRequiredService<T>() where T : notnull
        {
            return _provider.GetRequiredService<T>();
        }

        /// <summary>
        /// 获取容器内的服务集。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IEnumerable<T> GetServices<T>()
        {
            return _provider.GetServices<T>();
        }
    }
}
